package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.utils.SmsUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public void sendMsg(HttpServletRequest request, @RequestBody User user){
        int number= ValidateCodeUtils.generateValidateCode(4);
        String code = ""+number;
        log.info(code);
        request.getSession().setAttribute("code",code);
        //发送短信
//        SmsUtils.sendMessage(user.getPhone(), code);
        log.info(code+"发送成功");
    }

    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody Map<String,String> map) {
        String sessionCode = (String) request.getSession().getAttribute("code");
        log.info(sessionCode);
        String phone = map.get("phone");
        String code = map.get("code");
        //先从数据库里查找有没有这个电话号的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        //如果没有，判断验证码是否正确
        //正确就注册一个账户，返回success

        if (code.equals(sessionCode)) {
            if (user == null) {//没有这个账户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("验证码错误！");

    }
}
